package Send2ME::Dao::Rule;

use Exporter 'import';

@EXPORT = qw(RULE_TABLE createRule getRule getPredefinedRules updateRule deleteRule);

use Dancer ':syntax';
use Dancer::Plugin::Database;

use constant RULE_TABLE => 'rule';

# id | user_id | name | conditions | route_in | routes | priority

my $predefinedUserId = undef;

sub createRule {
	my $params = shift;
	return database->quick_insert(RULE_TABLE, $params);
}

sub getRule {
	my $params = shift;
	return database->quick_select(RULE_TABLE, $params, { order_by => 'priority' });
}

sub getPredefinedRules {
	unless ($predefinedUserId) {
		use Send2ME::Dao::User;
		my $user = getUser({recipient 	 => 'templates'});
		$predefinedUserId = $user->{id} if $user;	
	}
	
	unless ($predefinedUserId) {
		return undef;
	}
	
	return database->quick_select(RULE_TABLE, { user_id => $predefinedUserId }, { order_by => 'priority' });
}

sub updateRule {
	my $rule = shift;
	return database->quick_update(RULE_TABLE, { id => $rule->{id} },  $rule);
}

sub deleteRule {
	my $params = shift;
	return database->quick_delete(RULE_TABLE, $params);
}

1;